package model

import (
	"app/internal/pkg/ecode"
	"database/sql"
	"errors"

	"gorm.io/gorm"
)

type User struct {
	Account   uint           `gorm:"uniqueIndex;comment:账号"`
	Name      string         `gorm:"type:varchar(20);not null;comment:姓名"`
	Nickname  sql.NullString `gorm:"type:varchar(30);unique;comment:昵称"`
	Telephone sql.NullString `gorm:"type:varchar(15);unique;comment:手机号"`
	Email     sql.NullString `gorm:"type:varchar(50);unique;comment:邮箱"`
	Password  string         `gorm:"type:varchar(64);not null;comment:密码"`
	gorm.Model
}

// 获取用户
func GetUserByID(id uint) (user *User, err error) {
	err = db.Take(&user, id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, ecode.ERROR_USER_NOT_EXIST
	}
	return
}

// 创建用户
func CreateUser(user *User) (int64, error) {
	result := db.Create(user)
	return result.RowsAffected, result.Error
}

// 更新用户
func UpdateUser(user *User) (int64, error) {
	if _, err := GetUserByID(user.ID); err != nil {
		return 0, err
	}
	result := db.Model(user).Updates(user)
	return result.RowsAffected, result.Error
}

// 删除用户
func DeleteUser(id uint) (int64, error) {
	if _, err := GetUserByID(id); err != nil {
		return 0, err
	}
	result := db.Delete(&User{}, id)
	return result.RowsAffected, result.Error
}

// 获取用户，通过 account
func GetUserByAccount(account uint) (user *User, err error) {
	err = db.Take(&user, "account = ?", account).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, ecode.ERROR_USER_NOT_EXIST
	}
	return
}

// 获取用户列表，通过 name
func GetUsersByName(name string) (users *[]User, err error) {
	err = db.Where("name LIKE ?", "%"+name+"%").Find(users).Error
	return
}

// 获取用户列表，通过 nickname
func GetUsersByNickname(nickname string) (users *[]User, err error) {
	err = db.Where("nickname LIKE ?", "%"+nickname+"%").Find(users).Error
	return
}

// 获取用户列表，通过 telephone
func GetUsersByTelephone(telephone string) (users *[]User, err error) {
	err = db.Where("telephone LIKE ?", "%"+telephone+"%").Find(users).Error
	return
}
